import axios from 'axios'
import _ from 'lodash'
import _this from '../main'

var http = axios.create({
  baseURL: import.meta.env.VITE_BASEURL + '/api/',
  withCredentials: false,
  changeOrigin: false,
  headers: {
    'Content-Type': 'application/json',
  },
  validateStatus: function (status) {
    return status === 200 || status === 204
  },
})

http.interceptors.request.use(
  function (request) {
    var token = sessionStorage.getItem('token')
    var tenantID = sessionStorage.getItem('tenant')

    request.headers = {
      'Content-Type': 'application/json',
      Authorization: 'Bearer ' + token,
      TenantID: tenantID,
    }

    return request
  },
  function (error) {
    return Promise.reject(error)
  },
)

http.interceptors.response.use(
  function (response) {
    return response
  },
  function (error) {
    console.log(error)
    let status = error.response.status
    let data = error.response.data
    if (status == 422) {
      _this.$Notice.error({
        title: '数据模型传输异常！',
        desc: data.errors,
        duration: 0,
      })
    }
    if (status == 500) {
      _this.$Notice.error({
        title: '后台接口出现异常！',
        desc: data,
        duration: 0,
      })
    }
    if (status == 401) {
      _this.$Notice.warning({
        title: '身份信息已过期',
        desc: '为了你的账户安全，请重新登录...',
        duration: 5,
      })
      _this.$router.replace('/')
    }
    if (status == 403) {
      _this.$Notice.warning({
        title: '拒绝调用后台接口',
        desc: '您所在的角色暂无权限调用：' + data + '。<br/>请联系管理员予以授权！',
        duration: 0,
      })
    }
    return Promise.reject(error)
  },
)

function apiAxios(method, url, params, response) {
  http({
    method: method,
    url: url,
    data: method === 'POST' || method === 'PUT' ? params : null,
    params: method === 'GET' || method === 'DELETE' ? params : null,
  })
    .then(function (res) {
      response(res)
    })
    .catch(function (err) {
      response(err)
    })
}

function upload(url, params, response) {
  http({
    method: 'POST',
    url: url,
    data: null,
    params: params,
    headers: { 'Content-Type': 'multipart/form-data' },
  })
    .then(function (res) {
      response(res)
    })
    .catch(function (err) {
      response(err)
    })
}

function downloadStream(name, url, type, params, response) {
  http({
    method: 'POST',
    url: url,
    data: params,
    params: null,
    responseType: 'blob',
  })
    .then(function (res) {
      const link = document.createElement('a')
      const blob = new Blob([res.data], {
        type: type,
      })
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      link.setAttribute('download', `${name}.xlsx`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    })
    .catch(function (err) {
      response(err)
    })
}

export default {
  get: function (url, params, response) {
    return apiAxios('GET', url, params, response)
  },
  post: function (url, params, response) {
    return apiAxios('POST', url, params, response)
  },
  put: function (url, params, response) {
    return apiAxios('PUT', url, params, response)
  },
  delete: function (url, params, response) {
    return apiAxios('DELETE', url, params, response)
  },
  upload: function (url, params, response) {
    return upload(url, params, response)
  },
  excel: function (name, url, params, response) {
    return downloadStream(
      name,
      url,
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      params,
      response,
    )
  },
}
